package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseMaterialMapper;
import com.yuyou.tas.lesson.service.IBaseMaterialService;
import com.yuyou.tas.lesson.service.IBaseSectionService;
import com.yuyou.tas.lesson.service.ILessonMaterialService;
import com.yuyou.tas.lesson.vo.req.ReqAddBaseMaterial;
import com.yuyou.tas.lesson.vo.req.ReqUpdateBaseMaterial;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseMaterial;
import com.yuyou.tas.service.api.lesson.entity.BaseMaterial;
import com.yuyou.tas.service.api.lesson.entity.BaseSection;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.lesson.LessonBaseEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.DefindBeanUtils;
import com.yuyou.tas.util.tool.Sequence;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class BaseMaterialServiceImpl implements IBaseMaterialService {

    @Autowired
    private BaseMaterialMapper mapper;

    @Autowired
    private IBaseSectionService sectionService;

    @Autowired
    private ILessonMaterialService lessonMaterialService;

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public BaseMaterial selectByPrimaryKey(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo addMaterial(ReqAddBaseMaterial material, Long pId,  Integer isStan, LoginRedisObj user, Long organId) {
        BaseMaterial bm = new BaseMaterial();
        DefindBeanUtils.copyProperties(material,bm);
        bm.setId(Sequence.getSequence().nextId());
        bm.setAuthOrganizationId(organId);
        bm.setCreateTime(new Date());
        bm.setCreateUser(user.getUserId());
        bm.setIsStan(isStan);
        bm.setpId(pId);
        bm.setBaseSectionId(String.join(",",material.getBaseSectionId()));
        mapper.insert(bm);
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"插入成功",null);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo updatMaterial(ReqUpdateBaseMaterial material, Long pId, Integer isStan, LoginRedisObj user) {
        BaseMaterial bm = mapper.selectByPrimaryKey(material.getId());
        if(bm != null){
            if(material.getDataSubject() != null && !bm.getDataSubject().equals(material.getDataSubject())){//科目发生变化
                List<String> usedList = lessonMaterialService.findBaseMatInLesson(bm.getId());
                if(!CollectionUtils.isEmpty(usedList)){//该素材已经被引用
                    if(usedList.size() > 3){
                        List<String> list = usedList.stream().limit(3).collect(Collectors.toList());
                        throw new BusinessException("该素材已被课程：[ " + String.join(",",list) + "...等" +" ]使用，请先解除关系后再更改科目");
                    }else{
                        throw new BusinessException("该素材已被课程：[ " + String.join(",",usedList) + " ]使用，请先解除关系后再更改科目");
                    }
                }
            }
            DefindBeanUtils.copyProperties(material,bm);
            bm.setIsStan(isStan);
            bm.setpId(pId);
            if(material != null && material.getBaseSectionId() != null){
                bm.setBaseSectionId(String.join(",",material.getBaseSectionId()));
            }
            mapper.updateByPrimaryKeySelective(bm);
        }
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"修改成功",null);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo delMaterial(Long id){
        Integer usedCount = lessonMaterialService.findCountBaseMatInLesson(id);
        if(usedCount != null && usedCount > 0){
            List<String> usedList = lessonMaterialService.findBaseMatInLesson(id);
            throw new BusinessException("该素材已经被[" + usedList.get(0) + "]等,"+usedCount + "个课程所引用,请先解除关系,再删除");
        }

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"删除成功",null);
        mapper.deleteByPrimaryKey(id);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public int findMaterialCount(Pagination<DtoBaseMaterial> queryPgn) {
        return mapper.findMaterialCount(queryPgn);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public List<DtoBaseMaterial> findMaterialPageList(Pagination<DtoBaseMaterial> queryPgn) {
        List<DtoBaseMaterial> list = mapper.findMaterialPageList(queryPgn);

        Map<String , Object> conditon = new HashMap<>();
        conditon.put("isUse" , LessonBaseEnums.isEnableed.enabl.getValue());
        conditon.put("isStan" , 1);
        List<BaseSection> sections = sectionService.findSectionName(conditon);//获取本机构和标准的年级名称
        Map<Long , BaseSection> sectionMap = BeanUtils.toMap(sections , "id");

        for (DtoBaseMaterial b:list) {
            String sectionName = "";
            if(b.getBaseSectionId() != null && !b.getBaseSectionId().equals("")){
                String[] ids = b.getBaseSectionId().split(",");
                for (int i = 0 ; i < ids.length ; i++){
                    if(sectionMap.containsKey( Long.valueOf(ids[i]))){
                        sectionName = sectionName + sectionMap.get(Long.valueOf(ids[i])).getName() + ",";
                    }
                }
            }
            if(!sectionName.equals("")){//去调最后的逗号
                sectionName = sectionName.substring(0,sectionName.length()-1);
                b.setSectionNames(sectionName);
            }
        }
        return list;
    }

    @Override
    public BaseMaterial selectByPKandOrgan(Long id, Long authOrganizationId) {
        return mapper.selectByPKandOrgan(id, authOrganizationId);
    }
}